<template>
  <div class="wrapper">
    <div class="header">
      <a-form-model layout="inline" :model="searchForm" @submit="handleSubmit" @submit.native.prevent>
        <a-form-model-item label="任务名称">
          <a-input v-model="searchForm.name" placeholder="输入任务名称"> </a-input>
        </a-form-model-item>
        <a-form-model-item>
          <a-button class="border-radius-4" type="primary" icon="search" @click="handleSearch"> 搜索 </a-button>
        </a-form-model-item>
      </a-form-model>
    </div>
    <div class="body">
      <a-button class="operateButtons" type="primary" icon="plus" @click="showAddModal"> 新建任务 </a-button>
      <a-table :columns="columns" size="middle" :data-source="data" class="custom-table">
        <template slot="labels" slot-scope="labels">
          <template v-if="labels">
            <a-tag v-for="label in labels.split(', ')" :key="label">
              {{ label }}
            </a-tag>
          </template>
        </template>
        <span slot="action" slot-scope="text, record, index">
          <!-- <a-button type="link" style="padding-left: 0" @click="handleGetInfo(record)"> 详情 </a-button> -->
          <!-- <a-divider type="vertical" /> -->
          <a-button class="px-0" type="link" @click="handleDelete(record)"> 删除 </a-button>
        </span>
      </a-table>
    </div>
    <div class="footer"></div>
    <edit ref="edit" @success="getData" />
  </div>
</template>

<script>
import { listModels, addModel, deleteModel } from '../../../api/model'
import { formatTime } from '../../../utils/util'
import notification from 'ant-design-vue/es/notification'
import edit from './editMission'
const columns = [
  {
    title: '序号',
    dataIndex: 'index',
    key: 'index',
    align: 'center',
    width: 80,
    customRender: (text, record, index) => `${index + 1}`,
  },
  {
    title: '任务名称',
    dataIndex: 'name',
    key: 'name',
  },
  {
    title: '标注场景',
    dataIndex: 'scene',
    key: 'scene',
  },
  {
    title: '状态',
    dataIndex: 'status',
    key: 'status',
  },
  {
    title: '进度',
    dataIndex: 'progress',
    key: 'progress',
  },
  {
    title: '任务描述',
    dataIndex: 'remark',
    key: 'remark',
  },
  {
    title: '标签',
    dataIndex: 'labels',
    key: 'labels',
    scopedSlots: { customRender: 'labels' }, // 添加自定义渲染
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    key: 'createTime',
  },
  {
    title: '操作',
    key: 'action',
    width: 180, // 设置序号列的宽度
    scopedSlots: { customRender: 'action' },
  },
]
export default {
  name: 'Assessment',
  components: {
    edit,
  },
  data() {
    return {
      data: [],
      formInline: {
        user: '',
        password: '',
      },
      columns,
      visible: false,
      isEdit: false,
      modalTile: '新增',
      labelCol: { span: 6 },
      wrapperCol: { span: 14 },
      form: {
        name: '',
        labels: undefined,
        indicator: undefined,
        savePath: '',
      },

      addModalTitle: '新增模型',
      addVisible: false,
      addForm: {
        name: '',
      },
      searchForm: {
        name: '',
      },
      labelOptions: [
        { label: '标签1', value: 'tag-1' },
        { label: '标签2', value: 'tag-2' },
      ],
      scenarioOptions: [
        { label: '文本分类标注', value: 'text-classification' },
        { label: '命名实体识别', value: 'ner' },
        { label: '关系抽取', value: 'relation-extraction' },
        { label: '文本聚类', value: 'text-clustering' },
        { label: '情感分析', value: 'sentiment-analysis' },
      ],
    }
  },
  methods: {
    generateRandomId() {
      const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
      let id = ''
      for (let i = 0; i < 4; i++) {
        const randomIndex = Math.floor(Math.random() * chars.length)
        id += chars[randomIndex]
      }
      return id
    },
    getCurrentTime() {
      const now = new Date()

      const year = now.getFullYear()
      const month = String(now.getMonth() + 1).padStart(2, '0') // 月份从0开始，因此+1
      const day = String(now.getDate()).padStart(2, '0')

      const hours = String(now.getHours()).padStart(2, '0')
      const minutes = String(now.getMinutes()).padStart(2, '0')
      const seconds = String(now.getSeconds()).padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    handleSubmit(e) {
      console.log(this.formInline)
    },
    showAddModal() {
      this.$refs.edit.showModal()
    },
    handleOk(e) {
      console.log(this.form)
      this.data = [{ ...this.form, modalId: this.generateRandomId(), createTime: this.getCurrentTime() }, ...this.data]
      this.visible = false
      this.handleReset()
    },
    handleCancel() {
      this.visible = false
      this.handleReset()
    },
    handleReset() {
      this.form = {
        name: '',
        labels: '',
        indicator: '',
        savePath: '',
      }
    },
    handleEdit(row) {
      this.isEdit = true
      this.form = {
        ...row,
      }
      // this.showAddModal()
    },
    handleDelete(record) {
      this.$confirm({
        title: '确认删除',
        content: `确定要删除任务"${record.name}"吗？`,
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          // 直接从本地数据中移除
          this.data = this.data.filter((item) => item.id !== record.id)
          this.$message.success('删除成功')
        },
      })
    },
    handleSearch() {
      // 如果搜索框为空,显示所有数据
      if (!this.searchForm.name) {
        this.pageModels()
        return
      }

      // 本地过滤数据
      const searchText = this.searchForm.name.toLowerCase()
      this.data = this.data.filter((item) => item.name.toLowerCase().includes(searchText))
    },
    onSubmit() {
      console.log('submit!', this.form)
    },
    pageModels() {
      let requestResult = []

      this.data = [
        {
          id: 122323,
          name: '特征工程任务A',
          scene: '文本分类标注',
          status: '进行中',
          progress: '75%',
          remark: '系统性能测试评估',
          labels: '高优先级',
          createTime: '2024-03-20 14:30:00',
        },
      ]
    },
    handleAddOk(e) {
      console.log(e)
      const newThis = this
      addModel(newThis.addForm)
        .then((result) => {
          newThis.addVisible = false
          newThis.pageModels()
          notification.success({
            message: '新增成功',
            description: `新增成功`,
          })
        })
        .catch((error) => {
          newThis.addVisible = false
          notification.error({
            message: '新增失败',
            description: `新增失败`,
          })
        })
    },
    handleAddCancel() {
      this.addVisible = false
    },
    handleGetInfo(record) {
      this.$refs.detail.showModal(record)
    },
    getData(d) {
      // 处理标签
      if (d.labels) {
        const labelValues = d.labels.split(',')
        const labelTexts = labelValues.map((value) => {
          const option = this.labelOptions.find((opt) => opt.value === value)
          return option ? option.label : value
        })
        d.labels = labelTexts.join(', ')
      }

      // 处理标注场景，将value转换为对应的label
      if (d.scenario) {
        const scenarioOption = this.scenarioOptions.find((opt) => opt.value === d.scenario)
        d.scene = scenarioOption ? scenarioOption.label : d.scenario
      }

      // 添加默认状态和进度
      d.status = '进行中'
      d.progress = '0%'

      console.log(d)
      this.data = [d, ...this.data]
    },
  },
  mounted() {
    this.pageModels()
  },
}
</script>

<style lang="less" scoped>
@import '../index.less';
</style>
